package org.zebra.tenant.beansearch;

import cn.zhxu.bs.SearchSql;
import cn.zhxu.bs.SqlInterceptor;
import cn.zhxu.bs.param.FetchType;
import org.zebra.tenant.TenantHelper;

import java.util.Map;

/**
 * beansearch 多租户
 *
 * @author zhanghongbin
 */
public class BeanSearchTenantSqlInterceptor implements SqlInterceptor {

    private BeanSearchTenantLineInnerInterceptor beanSearchTenantLineInnerInterceptor;

    public BeanSearchTenantSqlInterceptor(BeanSearchTenantLineInnerInterceptor beanSearchTenantLineInnerInterceptor) {
        this.beanSearchTenantLineInnerInterceptor = beanSearchTenantLineInnerInterceptor;
    }

    @Override
    public <T> SearchSql<T> intercept(SearchSql<T> searchSql, Map<String, Object> map, FetchType fetchType) {
        if (TenantHelper.isEnabled() && !TenantHelper.isIgnore()) {
            String listSql = beanSearchTenantLineInnerInterceptor.parserMulti(searchSql.getListSqlString(), null);
            searchSql.setListSqlString(listSql);
            if (!searchSql.getClusterSqlString().equals("")) {
                String clusterSql =
                        beanSearchTenantLineInnerInterceptor.parserMulti(searchSql.getClusterSqlString(), null);
                searchSql.setClusterSqlString(clusterSql);
            }
        }
        return searchSql;
    }
}
